<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <el-input v-model="form.rule_name" placeholder="规则名称" clearable style="max-width: 338px" />

        <VXSelect v-model="form.status" placeholder="状态" clearable dictionary="wms_preferred_status" />

        <SelectPlatformSiteShop multiple class="lp-SelectPlatformSiteShop" :showRule="[true, false, false]" v-model:platform="form.platform_ids" />

        <SelectWarehouse multiple collapse-tags placeholder="发货仓库" style="max-width: 200px" v-model="form.wms_ids" />

        <SelectShippingMethod placeholder="运输方式" v-model="form.shipping_ids" multiple collapseTags style="width: 240px" />

        <select-personnel v-model="form.creator_ids" multiple clearable placeholder="创建人" />

        <VGroup>
          <div class="v-group-item">创建时间</div>
          <el-date-picker
            v-model="form.dateRange.value"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 400px"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime2"
          />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton type="primary" @click="add" v-hasPermi="[orderStrategyAuthList.logistics_preferred.add]">
          <div class="dk-iconfont icon-Plus"></div>
          新增
        </VButton>
        <VButton @click="handleStatus(1)" v-hasPermi="[orderStrategyAuthList.logistics_preferred.enable]">
          <div class="dk-iconfont icon-CircleCheck text-[#3487FF]"></div>
           启用
        </VButton>
        <VButton @click="handleStatus(2)" v-hasPermi="[orderStrategyAuthList.logistics_preferred.disable]">
          <div class="dk-iconfont icon-Disabled text-[red]"></div>
          禁用
        </VButton>
      </template>
    </VTable>
    <VLog ref="logRef" :api="LogAPIfn" />

    <Vedit ref="edit" :title="editTitle" class="dialogPublic" @confirm="editConfirm"> </Vedit>
  </VPage>
</template>

<script setup lang="jsx" name="Account">
import { organizationList, overallOptions } from "@/api/public"
import Vedit from "./components/edit"
import api from "./api"
import VLog from "@/components/VLog"
import { orderStrategyAuthList } from "@/Auth/order-strategy.js"
import { ElMessage, ElMessageBox } from "element-plus"
import { onMounted, ref, toRefs } from "vue"
import SelectPersonnel from "@/components/SelectPersonnel/index.vue"
import SelectWarehouse from "@/components/Selects/SelectWarehouse/index.vue"
import SelectPlatformSiteShop from "@/components/Selects/SelectPlatformSiteShop/index.vue"
import SelectShippingMethod from "@/components/Selects/SelectShippingMethod/index.vue"
const defaultTime2 = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 59)]
const edit = ref()
const data = reactive({
  organizationData: [],
  cascaderProps: {
    emitPath: false,
    multiple: true,
    label: "name",
    value: "user_id",
    children: "sub",
  },
  editTitle: "新增",
  statusOption: [],
})
const { organizationData, editTitle, statusOption } = toRefs(data)
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
const currentRow = ref({})
const optionsList = ref({
  platform: [],
  status: [],
})
const organizationListF = () => {
  organizationList().then((res) => {
    organizationData.value = res.data
  })
}

const LogAPIfn = ref(() => ({}))

const handleLog = (id) => {
  LogAPIfn.value = (dtd) => api.oplog({ ...dtd, tag: "order_wms_preferred", business_id: id })
  // logRef?.value.tableColumns()
  logRef?.value.open({ id })
  let fields = {
    user: "create_user",
    time: "created_at",
    content: "content",
  }
  logRef?.value.setFields(fields)
}

//编辑
const ruleEdit = (row, type = "edit") => {
  editTitle.value = "编辑"
  edit.value.open(row, type)
}
//新增
const add = () => {
  editTitle.value = "新增"
  edit.value.open()
}
const editConfirm = () => {
  setTimeout(() => {
    query()
  }, 200)
}
//删除
const profitSettingDeleteF = (id) => {
  ElMessageBox.confirm("此操作将永久删除该项, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "oms-message-confirm-button",
  }).then(async () => {
    try {
      api.delete(id).then((res) => {
        ElMessage.success("删除成功")
        query()
      })
    } catch (e) {
      throw Error(e)
    }
  })
}

//禁用
const handleStatus = (status) => {
  if (!getSelectRow().length) {
    return false
  }
  const arr = getSelectRow()
  api.status({ ids: arr, status }).then((res) => {
    ElMessage({
      message: `${status === 1 ? "启用" : "禁用"}成功！`,
      type: "success",
    })
    query()
  })
}
// 查询
const query = () => {
  setTimeout(() => {
    tableRef?.value.query()
  }, 200)
}
//打开详情
const showDetail = () => {
  // useRouter/oms/basic-setup/order-source
}

const initSelectOptions = async () => {
  const res = await overallOptions({
    option: "new",
    params: ["wms_preferred_status"],
  })
  const { wms_preferred_status } = res.data
  optionsList.value.status = wms_preferred_status
}

import { getAloneEnum } from "@/utils/enumUtils"
const originOption = ref({})
//获取下拉数据
onMounted(async () => {
  initSelectOptions().then(() => {
    setTimeout(() => {
      overallOptions({ params: ["base.orderCommission"] }).then((res) => {
        statusOption.value = res.data.baseOrderCommission.status
      })
    }, 1000)
  })

  let optData = await getAloneEnum(["platform"])
  originOption.value.platform = Object.fromEntries(optData?.platform.map((v) => [v.value, v.label]))
})
//获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  const arr = []
  getCheckboxRecords.map((e) => {
    arr.push(e.id)
  })
  return arr
}
// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      rule_name: "",
      status: "",
      platform_ids: [],
      wms_ids: [],
      shipping_ids: [],
      creator_ids: [],
      dateRange: { type: "create_date", value: [], range: true }, // 组合+日期范围
    },
  },
  showOverflow: true,
  columns: [
    { type: "checkbox", fixed: "left", width: 60 },
    { field: "id", title: "ID", width: 100 },
    { field: "rule_name", title: "规则名称", width: 240 },
    { field: "choose_type_desc", title: "物流优选", width: 200 },
    { field: "priority", title: "优先级", minWidth: 100 },
    {
      field: "platform_id_desc",
      title: "平台",
      minWidth: 100,
      slots: {
        default: ({ row }) => <VText value={originOption.value.platform?.[row.platform_id]} />,
      },
    },
    { field: "site", title: "站点", minWidth: 220 },
    {
      title: "状态",
      field: "status_text",
      width: 100,
      slots: {
        default: ({ row }) => <VStatus value={row.status == 1} />,
      },
    },
    { field: "creator", title: "创建人", width: 150 },
    { field: "create_time", title: "创建时间", width: 170 },
    { field: "update_time", title: "修改时间", width: 170 },
    {
      title: "操作",
      width: 150,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return [
            <div class="flex flex-wrap">
              <el-button link type="primary" class="ml-3" onClick={() => ruleEdit(row)} v-hasPermi={[[orderStrategyAuthList.logistics_preferred.edit]]}>
                编辑
              </el-button>
              <el-button link type="primary" onClick={() => ruleEdit(row, "copy")} v-hasPermi={[[orderStrategyAuthList.logistics_preferred.edit]]}>
                复制
              </el-button>

              <el-button link type="primary" onClick={() => handleLog(row.id)} v-hasPermi={[[orderStrategyAuthList.logistics_preferred.log]]}>
                日志
              </el-button>
              <el-button link type="danger" onClick={() => profitSettingDeleteF(row.id)} v-hasPermi={[[orderStrategyAuthList.logistics_preferred.delete]]}>
                删除
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page, form }) => {
        if (form.create_date && form.create_date.start) {
          form.create_date = [form.create_date.start, form.create_date.end]
        }
        let res = await api.query({ ...form, ...page })
        res.data.forEach((item) => {
          item.site = item.site?.join()
        })
        return res
      },
    },
  },
})
organizationListF()
</script>
<style lang="scss" scoped>
:deep(.lp-SelectPlatformSiteShop) {
  .sel-platform-site-shop-item {
    margin-bottom: unset !important;
  }
}
</style>
